<script setup lang="ts">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import { PlusSearch, type PlusColumn } from "plus-pro-components";
import { ElMessage } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import dialogForms, { type FormProps } from "./handle.vue";
import { handleWithdraw, getWithdrawList } from "@/api/user";
import { utils, writeFile } from "xlsx";
import { formatDate } from "@/utils/common";
defineOptions({
  name: "UserWithdraw"
});
import { useMenu } from "@/utils/power";
const power = useMenu(["exportExcel", "handle"]);

const tableRef = ref();
const multipleSelection = ref([]);
const toggleSelection = (rows?: any) => {
  const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
  if (rows) {
    rows.forEach(row => {
      toggleRowSelection(row, undefined);
    });
  } else {
    clearSelection();
  }
};

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "金额大于",
    labelWidth: 100,
    width: 200,
    prop: "xAmount",
    valueType: "input-number",
    placeholder: "查询提现金额大于当前值的结果"
  },
  {
    label: "金额小于",
    labelWidth: 100,
    width: 200,
    prop: "dAmount",
    valueType: "input-number",
    placeholder: "查询提现金额小于当前值的结果"
  },
  {
    label: "选择时间范围",
    labelWidth: 120,
    width: 600,
    prop: "dateRange",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "daterange",
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "处理时间",
    labelWidth: 120,
    width: 600,
    prop: "handleTime",
    valueType: "date-picker",
    tooltip: "请选择时间",
    fieldProps: {
      type: "date",
      placeholder: "处理时间",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "待审核",
        value: "0",
        color: "red"
      },
      {
        label: "已通过",
        value: "1",
        color: "blue"
      },
      {
        label: "驳回",
        value: "2",
        color: "green"
      }
    ]
  },
  {
    label: "是否支付宝",
    prop: "isZFB",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "全部",
        value: 0,
        color: "red"
      },
      {
        label: "支付宝",
        value: 1,
        color: "blue"
      },
      {
        label: "银行卡",
        value: 2,
        color: "green"
      }
    ]
  }
];

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  balance,
  unsettledAmount,
  params,
  loadData,
  onSizeChange,
  onKeywordChange,
  onCurrentChange
} = useColumns();
const columnsRef = computed(() => {
  if (power.value.handle) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (
    target.prop == "keyWord" ||
    target.prop == "xAmount" ||
    target.prop == "dAmount"
  ) {
    return;
  }
  onKeywordChange(value);
};

const handleSelectionChange = selection => {
  multipleSelection.value = selection;
};
function doClick(rows?) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    rows
  );
  const status = rows?.length === 1 ? rows[0].status : "0";
  const remark = rows?.length === 1 ? rows[0].remark : "";
  addDialog({
    title: "处理提现",
    width: "30%",
    draggable: true,
    sureBtnLoading: true,
    contentRenderer: () => dialogForms,
    props: {
      formInline: {
        cIds: rows?.map(v => v.id) ?? [],
        status: status,
        remark: remark
      }
    },
    beforeSure: (done, { options, index }) => {
      const { formInline } = options.props;
      console.log("options", formInline);
      const data = Object.assign({}, formInline);
      if (data.remark == "其它") {
        if (!data.remark2) {
          ElMessage.error("请输入其它备注");
          return;
        }
        data.remark = data.remark2;
      }

      handleWithdraw(data)
        .then(() => {
          done();
          loadData();
          ElMessage.success("处理成功");
        })
        .catch(e => {
          done();
          console.log("e", e);
        });
    }
  });
}
const fullscreenLoading = ref(false);

const exportExcel = async () => {
  try {
    const postData = Object.assign({}, params.value);
    postData.pageSize = 5000;
    postData.page = 1;
    const resData = await getWithdrawList(postData);
    const data = resData.data.items;

    const dataKeys: string[] = [
      "ckr",
      "sfz",
      "account",
      "khh",
      "yhmc",
      "yhkh",
      "zfb",
      "real_num",
      "total_num",
      "handleTime",
      "created_at"
    ];
    const titleList: string[] = [
      "姓名",
      "身份证",
      "账号",
      "开户行",
      "银行详情",
      "银行卡号",
      "支付宝",
      "实际到账",
      "提现金额",
      "处理时间",
      "提现时间"
    ];
    const res: string[][] = data.map(item => {
      const arr = [];
      dataKeys.forEach(column => {
        arr.push(item[column]);
      });
      return arr;
    });
    res.unshift(titleList);
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `${formatDate(new Date())} 提现报表.xlsx`);
    ElMessage.success(`导出成功${data.length}条`);
  } catch (error) {
    console.log(error, "exportError");
  }
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>提现列表</h3>
        </template>
        <template #content>
          <div class="flex flex-row">
            备用金余额:{{ balance }}
            <div class="w-10" />
            待计算金额:{{ unsettledAmount }}
          </div>
        </template>
        <template v-if="power.exportExcel" #extra>
          <el-popconfirm
            title="是否确认导出(默认导出最大5000条数据)"
            @confirm="exportExcel"
          >
            <template #reference>
              <el-button
                v-loading.fullscreen.lock="fullscreenLoading"
                type="primary"
                size="default"
                class="mb-4!"
              >
                导出Excel
              </el-button>
            </template>
          </el-popconfirm>
        </template>
        <PlusSearch
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @reset="handleReset"
          @change="handleChange"
          @search="handleSearch"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :fit="true"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @selection-change="handleSelectionChange"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #fund="{ row }">
        <el-descriptions :column="1">
          <el-descriptions-item label="实际到账">{{
            row.real_num
          }}</el-descriptions-item>
          <el-descriptions-item label="提现金额">{{
            row.total_num
          }}</el-descriptions-item>
          <el-descriptions-item label="优惠点">{{
            row.coupon_num
          }}</el-descriptions-item>
          <el-descriptions-item label="提现费用">{{
            row.total_fee
          }}</el-descriptions-item>
        </el-descriptions>
      </template>
      <template #bank="{ row }">
        <div v-if="row.cash_type != 3" class="flex flex-col wrap-text">
          <span>开户行： {{ row.khh }}</span>
          <span>银行详情： {{ row.yhmc }}</span>
          <span>卡号： {{ row.yhkh }}</span>
          <span v-if="row.ckr.length <= 4">身份证： {{ row.sfz }}</span>
          <span v-else>社会信用码： {{ row.sfz }}</span>
        </div>
        <div v-else>潮付</div>
      </template>
      <template #status="{ row }">
        <el-tag v-if="row.status == '1'" type="success">已通过</el-tag>
        <el-tag v-else-if="row.status == '2'" type="danger">驳回</el-tag>
        <el-tag v-else type="primary">待审核</el-tag>
      </template>
      <template #receipt="{ row }">
        <el-button
          v-if="row.receipt && row.receipt.length > 0"
          type="primary"
          tag="a"
          :href="row.receipt"
          target="_blank"
          rel="noopener noreferrer"
        >
          查看
        </el-button>
        <el-tag v-else type="danger">无</el-tag>
      </template>
      <template v-if="power.handle" #operation="{ row }">
        <el-button
          v-if="row.status == '0'"
          link
          type="primary"
          size="small"
          @click="doClick([row])"
        >
          处理
        </el-button>
        <el-tag v-else type="success">已处理</el-tag>
      </template>
    </pure-table>

    <div v-if="power.handle" style="margin-top: 20px">
      <el-button @click="toggleSelection(dataList)">全选</el-button>
      <el-button @click="toggleSelection()">取消所有</el-button>
      <el-button @click="doClick(multipleSelection)">处理所选</el-button>
    </div>
  </ElCard>
</template>

<style scoped>
:deep(.el-descriptions),
:deep(.el-descriptions__table tr) {
  --el-card-bg-color: transparent !important;
  --el-fill-color-blank: transparent !important;
  background: transparent !important;
}
.wrap-text {
  white-space: normal !important; /* 允许自动换行 */
  word-break: break-all; /* 强制换行 */
}
</style>
